package com.idconfirmsystem.fragment;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.DocumentException;
import org.kymjs.kjframe.http.HttpCallBack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.dtr.zxing.activity.CaptureActivity;
import com.idconfirmsystem.Conf;
import com.idconfirmsystem.R;
import com.idconfirmsystem.adapter.BagVerifyQueryAdapter;
import com.idconfirmsystem.lib.StringUtil;
import com.idconfirmsystem.model.BackModel;
import com.idconfirmsystem.model.BackModelList;
import com.idconfirmsystem.model.BagVerifyInfo;
import com.idconfirmsystem.model.BagVerifyInfoList;
import com.idconfirmsystem.model.BagVerifyInfoQuery;
import com.idconfirmsystem.model.BagVerifyUp;
import com.idconfirmsystem.model.QueryRet;
import com.idconfirmsystem.model.UserBean;
import com.idconfirmsystem.remote.ConfirmApi;
import com.idconfirmsystem.util.DateUtil;
import com.idconfirmsystem.util.XmlUtils;

/**
 * 箱包核验
 * 
 * @author Administrator
 * 
 */
public class BagVerifyFragment extends Fragment {

	private ListView bagListView;
	private Spinner isEmptySpinner;
	private TextView tvBranchNum;
	private EditText tvBagNum;
	private EditText tvBagSeal;

	private Button btnCheck;
	private Button btnCancel;
	private Button btnNumScan;
	private Button btnSealScan;

	private List<BagVerifyInfo> bVerifyInfos;
	private BagVerifyInfoQuery query;
	private BagVerifyQueryAdapter adapter;
	QueryRet<BagVerifyInfoList> qResult;
	
	private String upmethod="BankService/addVerifyBag";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_bag_verify, container, false);
		initWidget(view);
		// initData();
		queryData();
		tvBranchNum.setText(UserBean.getInstance().getBranchNumber());
		return view;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
//		super.onActivityResult(requestCode, resultCode, data);
		if(data==null) {
			return;
		}
		String zcode = data.getStringExtra("zcode");
		if(resultCode==Conf.ResultCode.BAG_NUM_SCAN){
			tvBagNum.setText(zcode);
		}else if (resultCode==Conf.ResultCode.BAG_SEAL_SCAN) {
			tvBagSeal.setText(zcode);
		}
	}

	public void queryData() {

		if (query == null) {
			query = new BagVerifyInfoQuery();
		}
		if (UserBean.getInstance().getBranchNumber() != null) {
			query.setBranchNo(UserBean.getInstance().getBranchNumber());
		}
		query.setDate(DateUtil.getCurrentDateByFormat("yyyyMMdd"));
		// TODO Auto-generated method stub
		String serviceMethod = "BankService/searchVerifyInfo";
		ConfirmApi.queryData(query, serviceMethod, qcallback);
	}

	HttpCallBack qcallback = new HttpCallBack() {

		@Override
		public void onFailure(int errorNo, String strMsg) {
			// TODO Auto-generated method stub
			super.onFailure(errorNo, strMsg);
		}

		@Override
		public void onSuccess(String t) {
			// TODO Auto-generated method stub
			super.onSuccess(t);
			try {
				qResult = XmlUtils.toBean(BagVerifyInfoList.class, t);
				updateList();
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	};
	public void datatoserver() {
		String bgnum = tvBagNum.getText().toString();
		if (StringUtil.isEmpty(bgnum)) {
			toast("箱包编号不能为空");
			return;
		}
		String bagseal = tvBagSeal.getText().toString();
		if (StringUtil.isEmpty(bagseal)) {
			toast("箱包签封号不能为空");
			return;
		}
		BagVerifyUp vo=new BagVerifyUp();
		vo.setBagSealNo(bagseal);
		vo.setBagsNumber(bgnum);
		vo.setBranchNo(tvBranchNum.getText().toString());
		vo.setLoginUserId(UserBean.getInstance().getUserName());
		
		ConfirmApi.pushData(vo, upmethod, ucallBack);
	}
	HttpCallBack ucallBack=new HttpCallBack() {

		@Override
		public void onFailure(int errorNo, String strMsg) {
			// TODO Auto-generated method stub
			super.onFailure(errorNo, strMsg);
			toast(errorNo+":"+strMsg);
		}

		@Override
		public void onSuccess(String t) {
			// TODO Auto-generated method stub
			super.onSuccess(t);
			try {
				QueryRet<BackModelList> ret = XmlUtils.toBean(BackModelList.class, t);
				BackModel ss = ret.getResult().getBackModels().get(0);
				toast(ss.getAae317());
				Log.d("bagverify", ss.getAae314());
				if(Integer.parseInt(ss.getAae314())==1){//核对成功则返回，失败则不管
					clear();
				}
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	};

	public void initWidget(View view) {
		bagListView = (ListView) view.findViewById(R.id.lv_bag);
		isEmptySpinner = (Spinner) view.findViewById(R.id.sp_isempty);
		tvBranchNum = (TextView) view.findViewById(R.id.tv_branch_num);
		tvBagNum = (EditText) view.findViewById(R.id.et_bag_num);
		tvBagSeal = (EditText) view.findViewById(R.id.et_bag_seal);

		btnCheck = (Button) view.findViewById(R.id.btn_check);
		btnCheck.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				datatoserver();
			}
		});
		btnCancel = (Button) view.findViewById(R.id.btn_cancel);
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				clear();
			}
		});
		btnNumScan = (Button) view.findViewById(R.id.btn_num_scan);
		btnNumScan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent it=new Intent(BagVerifyFragment.this.getActivity(),CaptureActivity.class);
				it.putExtra("resultcode", Conf.ResultCode.BAG_NUM_SCAN);
				startActivityForResult(it, Conf.ResultCode.BAG_NUM_SCAN);
			}
		});
		btnSealScan = (Button) view.findViewById(R.id.btn_seal_scan);
		btnSealScan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent it=new Intent(getActivity(),CaptureActivity.class);
				it.putExtra("resultcode", Conf.ResultCode.BAG_SEAL_SCAN);
				startActivityForResult(it, Conf.ResultCode.BAG_SEAL_SCAN);//
			}
		});
	}

	public void updateList() {
		if (qResult.getTotalnum() <= 0) {
			bVerifyInfos = new ArrayList<BagVerifyInfo>();
			Toast.makeText(getActivity(), "未查询到数据,暂展示测试数据", Toast.LENGTH_SHORT).show();
			/*
			 * for (int i = 0; i < 30; i++) {// testdata BagVerifyInfo
			 * itemBagVerifyInfo = new BagVerifyInfo();
			 * itemBagVerifyInfo.setArrival_time("2015090" + i);
			 * itemBagVerifyInfo.setBags_number("891000" + i);
			 * itemBagVerifyInfo.setBranch_number("XY100" + i);
			 * itemBagVerifyInfo.setCoordinate_title("兴业银行莲坂支行" + i); if (i % 2
			 * == 1) { itemBagVerifyInfo.setVerifyFlag("0"); } else {
			 * itemBagVerifyInfo.setVerifyFlag("1");
			 * itemBagVerifyInfo.setBags_seal_no
			 * (itemBagVerifyInfo.getBags_number() + "1000" + i);
			 * itemBagVerifyInfo
			 * .setVerifyTime(DateUtil.getCurrentDateByFormat("MM月dd日 hhmm")); }
			 * bVerifyInfos.add(itemBagVerifyInfo); }
			 */
		} else {
			bVerifyInfos = qResult.getResult().getBgInfos();
		}

		if (bVerifyInfos != null) {
			if (adapter == null) {
				adapter = new BagVerifyQueryAdapter(getActivity(), bagListView, bVerifyInfos);
				bagListView.setAdapter(adapter);
			} else {
				adapter.setBaglist(bVerifyInfos);
				adapter.notifyDataSetChanged();
			}
		}
	}

	BagVerifyQueryHandler myHandler = new BagVerifyQueryHandler();

	class BagVerifyQueryHandler extends Handler {
		public BagVerifyQueryHandler() {
		}

		public BagVerifyQueryHandler(Looper looper) {
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1001:// 加载数据
				updateList();
				break;

			default:
				break;
			}
		}

	}
	public void clear(){
		tvBagNum.setText("");
		tvBagSeal.setText("");
	}
	public void toast(String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
	}

}
